#!/usr/bin/perl
use strict;
use MIME::Lite;

my $mail_address = 'yourmail@address';

sub BEGIN {
    my $dir;
    require File::Spec;
    if (!($dir = $ENV{MT_HOME})) {
        if ($0 =~ m!(.*[/\\])!) {
            $dir = $1;
        } else {
            $dir = './';
        }
        $ENV{MT_HOME} = $dir;
    }
    unshift @INC, File::Spec->catdir($dir, 'lib');
    unshift @INC, File::Spec->catdir($dir, 'extlib');
}

eval {
    local $SIG{__WARN__} = sub { print "**** WARNING: $_[0]\n" };

    require MT;
    my $mt = MT->new() or die MT->errstr;

    my $cfg = $mt->{cfg};
    if ($cfg->ObjectDriver =~ /^DBI::mysql$/) {
	my $database	= $cfg->Database;
	my $dbuser	= $cfg->DBUser;
	my $dbpassword	= $cfg->DBPassword;
	my $dbhost	= $cfg->DBHost;
	system("mysqldump $database -u$dbuser -p$dbpassword -h$dbhost > $database.sql; zip -qm $database $database.sql");

	my $msg = MIME::Lite->new(From => $cfg->EmailAddressMain || 'root@localhost',
				  To => $mail_address,
				  Subject => 'MySQL backup',
				  Type => 'multipart/mixed');
	$msg->attach(Type => 'TEXT',
		     Data => 'Hello');
	$msg->attach(Type => 'application/octet-stream',
		     Path => "$database.zip",
		     Filename => "$database.zip",
		     Disposition => 'attachment');
	$msg->send();
	system("rm -f $database.zip");
    }
};
